<template>
  <div class="p-2">
    <transition :enter-active-class="proxy?.animate.searchAnimate.enter" :leave-active-class="proxy?.animate.searchAnimate.leave">
      <div v-show="showSearch" class="mb-[10px]">
        <el-card shadow="hover">
          <el-form ref="queryFormRef" :model="queryParams" :inline="true" label-width="100px">
            <el-form-item label="会员昵称" prop="userName">
              <el-input v-model="queryParams.userName" placeholder="请输入会员昵称" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="手机号" prop="userMobile">
              <el-input v-model="queryParams.userMobile" placeholder="请输入手机号" clearable @keyup.enter="handleQuery" />
            </el-form-item>
            <el-form-item label="领取时间" prop="createTimes">
              <el-date-picker
                v-model="queryParams.params.createTimes"
                :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
                class="!w-240px"
                end-placeholder="结束日期"
                start-placeholder="开始日期"
                type="daterange"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="优惠卷类型" prop="type">
              <el-select v-model="queryParams.type" placeholder="请选择优惠卷类型" clearable>
                <el-option v-for="dict in coupon_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="业务类型" prop="businessType">
              <el-select v-model="queryParams.businessType" placeholder="请选择业务类型" clearable>
                <el-option v-for="dict in coupon_business_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item label="平台类型" prop="plateType">
              <el-select v-model="queryParams.plateType" placeholder="请选择平台类型" clearable>
                <el-option v-for="dict in coupon_plate_type" :key="dict.value" :label="dict.label" :value="dict.value" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
              <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </div>
    </transition>

    <el-card shadow="never">
      <template #header>
        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="danger" plain icon="Delete" :disabled="multiple" @click="handleDelete()" v-hasPermi="['tearoom:coupon:remove']"
              >回收</el-button
            >
          </el-col>
          <el-col :span="1.5">
            <el-button type="warning" plain icon="Download" @click="handleExport" v-hasPermi="['tearoom:coupon:export']">导出</el-button>
          </el-col>
          <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>
      </template>

      <!-- Tab 选项：真正的内容在 Lab -->
      <el-tabs v-model="activeTab" type="card" @tab-change="onTabChange">
        <el-tab-pane v-for="tab in statusTabs" :key="tab.value" :label="tab.label" :name="tab.value" />
      </el-tabs>

      <el-table v-loading="loading" :data="couponList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="优惠劵编号" align="center" prop="id" v-if="false" />
        <el-table-column label="会员昵称" align="center" prop="userName" />
        <el-table-column label="手机号" align="center" prop="userMobile" width="120px" />
        <el-table-column label="优惠劵名称" align="center" prop="name" width="120px" />
        <el-table-column label="类型" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="coupon_type" :value="scope.row.type" />
          </template>
        </el-table-column>
        <el-table-column label="优惠" align="center" prop="type">
          <template #default="scope">
            <dict-tag :options="coupon_discount_type" :value="scope.row.type" />
            <div>{{ discountFormat(scope.row) }}</div>
          </template>
        </el-table-column>
        <el-table-column label="业务类型" align="center" prop="businessType">
          <template #default="scope">
            <dict-tag :options="coupon_business_type" :value="scope.row.businessType" />
          </template>
        </el-table-column>
        <el-table-column label="平台类型" align="center" prop="plateType">
          <template #default="scope">
            <dict-tag :options="coupon_plate_type" :value="scope.row.plateType" />
          </template>
        </el-table-column>
        <el-table-column label="领取方式" align="center" prop="takeType">
          <template #default="scope">
            <dict-tag :options="coupon_take_type" :value="scope.row.takeType" />
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" prop="status">
          <template #default="scope">
            <dict-tag :options="coupon_status" :value="scope.row.status" />
          </template>
        </el-table-column>
        <el-table-column label="领取时间" align="center" prop="createTime" width="170px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用时间" align="center" prop="useTime" width="170px">
          <template #default="scope">
            <span>{{ parseTime(scope.row.useTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="使用订单号" align="center" prop="useOrderId" width="225px" />
        <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-tooltip content="回收" placement="top">
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['tearoom:coupon:remove']">回收</el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" v-model:page="queryParams.pageNum" v-model:limit="queryParams.pageSize" @pagination="getList" />
    </el-card>
  </div>
</template>

<script setup name="Coupon" lang="ts">
import { listCoupon, getCoupon, delCoupon, addCoupon, updateCoupon } from '@/api/tearoom/coupon';
import { CouponVO, CouponQuery, CouponForm } from '@/api/tearoom/coupon/types';
import {
  CouponTemplateVO,
  CouponProceductScopeTypeEnum,
  CouponTemplateValidityTypeEnum,
  CouponTemplateTypeEnum
} from '@/api/tearoom/couponTemplate/types';
import { convertToInteger, formatToFraction, floatToFixed2 } from '@/utils/index';

const { proxy } = getCurrentInstance() as ComponentInternalInstance;
const { coupon_type, coupon_product_scope, coupon_plate_type, coupon_take_type, coupon_status, coupon_discount_type, coupon_business_type } =
  toRefs<any>(
    proxy?.useDict(
      'coupon_type',
      'coupon_product_scope',
      'coupon_plate_type',
      'coupon_take_type',
      'coupon_status',
      'coupon_discount_type',
      'coupon_business_type'
    )
  );

const couponList = ref<CouponVO[]>([]);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref<Array<string | number>>([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);

const queryFormRef = ref<ElFormInstance>();
const couponFormRef = ref<ElFormInstance>();

const dialog = reactive<DialogOption>({
  visible: false,
  title: ''
});

const activeTab = ref('all'); // Tab 筛选
const statusTabs = reactive([
  {
    label: '全部',
    value: 'all'
  },
  {
    label: '未使用',
    value: '1'
  },
  {
    label: '已使用',
    value: '2'
  },
  {
    label: '已过期',
    value: '3'
  }
]);

const initFormData: CouponForm = {
  id: undefined,
  templateId: undefined,
  name: undefined,
  usePrice: undefined,
  takeType: undefined,
  validStartTime: undefined,
  validEndTime: undefined,
  productScope: undefined,
  productScopeValues: undefined,
  discountPercent: undefined,
  discountPrice: undefined,
  discountLimitPrice: undefined,
  userId: undefined,
  status: undefined,
  useOrderId: undefined,
  useTime: undefined,
  userMobile: undefined,
  remark: undefined,
  type: undefined,
  plateType: undefined,
  hourCount: undefined,
  businessType: undefined
};
const data = reactive<PageData<CouponForm, CouponQuery>>({
  form: { ...initFormData },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    templateId: undefined,
    name: undefined,
    usePrice: undefined,
    takeType: undefined,
    validStartTime: undefined,
    validEndTime: undefined,
    productScope: undefined,
    productScopeValues: undefined,
    discountPercent: undefined,
    discountPrice: undefined,
    discountLimitPrice: undefined,
    userId: undefined,
    userName: undefined,
    userMobile: undefined,
    status: undefined,
    useOrderId: undefined,
    useTime: undefined,
    type: undefined,
    plateType: undefined,
    hourCount: undefined,
    params: {
      createTimes: []
    }
  },
  rules: {
    id: [{ required: true, message: '优惠劵编号不能为空', trigger: 'blur' }],
    templateId: [{ required: true, message: '优惠劵模板编号不能为空', trigger: 'blur' }],
    name: [{ required: true, message: '优惠劵名称不能为空', trigger: 'blur' }],
    usePrice: [{ required: true, message: '是否设置满多少金额可用，单位：分不能为空', trigger: 'blur' }],
    takeType: [{ required: true, message: '领取方式不能为空', trigger: 'change' }],
    validStartTime: [{ required: true, message: '生效开始时间不能为空', trigger: 'blur' }],
    validEndTime: [{ required: true, message: '生效结束时间不能为空', trigger: 'blur' }],
    productScope: [{ required: true, message: '商品范围不能为空', trigger: 'change' }],
    userId: [{ required: true, message: '用户编号不能为空', trigger: 'blur' }],
    status: [{ required: true, message: '优惠码状态；1-未使用；2-已使用；3-已失效不能为空', trigger: 'change' }],
    type: [{ required: true, message: '优惠类型1-代金劵2-折扣劵3-小时卷4-次数卷不能为空', trigger: 'change' }]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询优惠劵列表 */
const getList = async () => {
  loading.value = true;
  const res = await listCoupon(queryParams.value);
  couponList.value = res.rows;
  total.value = res.total;
  loading.value = false;
};

/** 取消按钮 */
const cancel = () => {
  reset();
  dialog.visible = false;
};

/** 表单重置 */
const reset = () => {
  form.value = { ...initFormData };
  couponFormRef.value?.resetFields();
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields();
  handleQuery();
};

/** 多选框选中数据 */
const handleSelectionChange = (selection: CouponVO[]) => {
  ids.value = selection.map((item) => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  dialog.visible = true;
  dialog.title = '添加优惠劵';
};

/** 修改按钮操作 */
const handleUpdate = async (row?: CouponVO) => {
  reset();
  const _id = row?.id || ids.value[0];
  const res = await getCoupon(_id);
  Object.assign(form.value, res.data);
  dialog.visible = true;
  dialog.title = '修改优惠劵';
};

/** 提交按钮 */
const submitForm = () => {
  couponFormRef.value?.validate(async (valid: boolean) => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.id) {
        await updateCoupon(form.value).finally(() => (buttonLoading.value = false));
      } else {
        await addCoupon(form.value).finally(() => (buttonLoading.value = false));
      }
      proxy?.$modal.msgSuccess('操作成功');
      dialog.visible = false;
      await getList();
    }
  });
};

/** 删除按钮操作 */
const handleDelete = async (row?: CouponVO) => {
  const _ids = row?.id || ids.value;
  await proxy?.$modal.confirm('是否确认删除优惠劵编号为"' + _ids + '"的数据项？').finally(() => (loading.value = false));
  await delCoupon(_ids);
  proxy?.$modal.msgSuccess('删除成功');
  await getList();
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy?.download(
    'tearoom/coupon/export',
    {
      ...queryParams.value
    },
    `coupon_${new Date().getTime()}.xlsx`
  );
};

// 格式化【优惠金额/折扣】
const discountFormat = (row: CouponVO) => {
  //代金券
  if (row.type === CouponTemplateTypeEnum.DJJ.type) {
    return `￥${floatToFixed2(row.discountPrice)}`;
  }
  //折扣卷
  if (row.type === CouponTemplateTypeEnum.ZKJ.type) {
    return `${row.discountPercent}%`;
  }
  //小时卷
  if (row.type === CouponTemplateTypeEnum.XSJ.type) {
    return `${row.hourCount}小时`;
  }
  //次数卷
  if (row.type === CouponTemplateTypeEnum.CSJ.type) {
    return `${row.discountPercent}%`;
  }
  return '未知【' + row.type + '】';
};

/** tab 切换 */
const onTabChange = (tabName) => {
  queryParams.value.status = tabName === 'all' ? undefined : tabName;
  getList();
};

onMounted(() => {
  getList();
});
</script>
